﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using Thinktecture.IdentityModel.Client;

namespace BnbjoyBackend.Site.Security
{
    public class TokenManager
    {
        private static TokenManager manager;
        private static object lockObj = new object();

        private TokenManager() { }

        public static TokenManager Instance
        {
            get
            {
                if (manager == null)
                {
                    lock (lockObj)
                    {
                        if (manager == null)
                        {
                            manager = new TokenManager();
                        }
                    }
                }

                return manager; ;
            }
        }

        private string ClientId
        {
            get
            {
                return ConfigurationManager.AppSettings["ClientId"] ?? "Web";
            }
        }

        private string Secret
        {
            get
            {
                return ConfigurationManager.AppSettings["Secret"] ?? "Web@bnbjoy";
            }
        }

        public string ApiUrl
        {
            get
            {
                return ConfigurationManager.AppSettings["ApiUrl"].TrimEnd('/') ?? "";
            }
        }

        public TokenResponse GetPublicAccessToken()
        {
            var client = new OAuth2Client(new Uri(this.ApiUrl + "/Token"), this.ClientId, this.Secret);
            var response = client.RequestClientCredentialsAsync().Result;
            return response;
        }

        public TokenResponse GetToken(string userName, string password, bool store30Days = false)
        {
            var client = new OAuth2Client(new Uri(this.ApiUrl + "/Token"), this.ClientId, this.Secret);
            TokenResponse response = null;
            if (!store30Days)
            {
                response = client.RequestResourceOwnerPasswordAsync(userName, password).Result;
            }
            else
            {
                var paramsDic = new Dictionary<string, string>();
                paramsDic.Add("store30Days", "true");
                response = client.RequestResourceOwnerPasswordAsync(userName, password, null, paramsDic).Result;
            }
            return response;
        }

        public TokenResponse RefreshToken(string refreshToken)
        {
            var client = new OAuth2Client(new Uri(this.ApiUrl + "/Token"), this.ClientId, this.Secret);
            var response = client.RequestRefreshTokenAsync(refreshToken).Result;
            return response;
        }
    }
}